/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.worldscale.xp.wslib.im.jabber.impl;

import java.util.Hashtable;

import net.worldscale.xp.wslib.im.jabber.JabberClient;
import net.worldscale.xp.wslib.wsxml.DomUtil;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * 
 * @author Kun
 */
final class MyMechanismManager {

	private static MyMechanismManager sInst;

	public static MyMechanismManager getInstance() {
		if (sInst == null) {
			final MyMechanismManager newInst = new MyMechanismManager();
			newInst.init();
			sInst = newInst;
		}
		return sInst;
	}

	private final Hashtable<String, MyMechanism> mMechanisms;

	private MyMechanismManager() {
		mMechanisms = new Hashtable<String, MyMechanism>();
	}

	public MyMechanism find(Element mechanisms) {
		final NodeList nl = mechanisms.getElementsByTagName("mechanism");
		for (int i = nl.getLength() - 1; i >= 0; i--) {
			final Element node = (Element) nl.item(i);
			final String name = DomUtil.getTextContent(node);
			final MyMechanism rlt = find(name);
			if (rlt != null) {
				return rlt;
			}
		}
		return null;
	}

	public MyMechanism find(String name) {
		return this.mMechanisms.get(name);
	}

	public void regMachanism(MyMechanism me) {
		if (me != null) {
			this.mMechanisms.put(me.getName(), me);
		}
	}

	private void init() {
		this.regMachanism(new MyMechanism() {

			@Override
			public String getName() {
				return "PLAIN";
			}

			@Override
			public MyMechanismEngine newEngine() {
				return new PLAIN();
			}
		});
		this.regMachanism(new MyMechanism() {

			@Override
			public String getName() {
				return " 暂不支持 X-GOOGLE-TOKEN";
			}

			@Override
			public MyMechanismEngine newEngine() {
				return new X_GOOGLE_TOKEN();
			}
		});
	}

	private static class PLAIN extends MyMechanismEngine {

		@Override
		public String authString(JabberClient.LoginContext lc) {
			final String host, user, psw;
			host = lc.getJID().getHost();
			user = lc.getJID().getUser();
			psw = lc.getPassword();
			String str = (user + '@' + host + '\0' + user + '\0' + psw);
			byte[] buf = str.getBytes();
			return Base64.encode(buf, 0, buf.length);
		}

		@Override
		public String challengeString(JabberClient.LoginContext lc,
				String requestString) {
			throw new UnsupportedOperationException("Not supported yet.");
		}
	}

	private static class X_GOOGLE_TOKEN extends MyMechanismEngine {

		@Override
		public String authString(JabberClient.LoginContext lc) {
			throw new UnsupportedOperationException("Not supported yet.");
		}

		@Override
		public String challengeString(JabberClient.LoginContext lc,
				String requestString) {
			throw new UnsupportedOperationException("Not supported yet.");
		}
	}
}
